<?php
/**
 * 文章收藏
 * Created by PhpStorm.
 * User: andy
 * Date: 2020/02/25
 * Time: 下午6:42
 */
namespace app\common\model;

use think\Model;
use think\Db;
class ArticleCollectModel extends Model
{
    const SHOW_STATUS=1; //正常
    const HIDE_STATUS=0; //无效

    protected $autoWriteTimestamp = true;

    public function article(){
        $field='article_id,title,author,link,click,good_numb,thumb,publish_time,cat_id';
        return $this->hasOne('ArticleModel','article_id','article_id')->field($field);
    }

    /**
     * 所有列表
     * @param array $where
     * @param int $pageSum
     * @return \think\Paginator
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getALL($where=[],$pageSum=0)
    {
        if($pageSum<=0){
            $pageSum=getSystem("pageSUM")?getSystem("pageSUM"):10;
        }

        $list=self::with('article')
            ->where($where)
            ->order('create_time desc')
            ->paginate($pageSum);

        foreach ($list as $item){
            $item["collectCount"]=self::where('article_id',$item->article_id)
                ->where("status",self::SHOW_STATUS)
                ->count();

            $item["msgCount"]=ArticleMessageModel::where('article_id',$item->article_id)
                ->where("status",ArticleMessageModel::SHOW_STATUS)
                ->count();
        }

        return $list;
    }

    /**
     * 删除
     * @param $id
     * @return array
     */
    public function del($id){

        $status=self::destroy($id);
        if($status){
            return ['status'=>1,'msg'=>'删除成功！'];
        }else{
            return ['status'=>0,'msg'=>'删除失败！'];
        }
    }

    /**
     * 增加
     * @param $data
     * @return array
     */
    public function adds($data){
        if(!self::chackAction($data)){
            return['status'=>0,'msg'=>'已存在！'];
        }

        $status = self::save($data);

        if($status){
            return['status'=>1,'msg'=>'增加成功！'];
        }else{
            return['status'=>0,'msg'=>'增加失败！'];
        }
    }

    /**
     * 检测当前是否重复
     * @param $data
     * @return bool
     */
    private static function chackAction($data){

        $count=self::where('user_id',$data['user_id'])
            ->where('article_id',$data['article_id'])
            ->count();

        if($count>0){
            return false;
        }else{
            return true;
        }
    }


}